package com.gm.wholesale.db;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.gm.wholesale.db.order.bean.DBOrderBean;
import com.gm.wholesale.db.order.bean.DBOrderContentBean;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
    private static final String DATABASE_NAME = "gm.db";
    private static final int DATABASE_VERSION = 1;

    private Dao<DBOrderContentBean, Long> orderDao = null;

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    /**
     * 创建SQLite数据库
     */
    @Override
    public void onCreate(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource) {
        try {
            TableUtils.createTable(connectionSource, DBOrderContentBean.class);
            TableUtils.createTable(connectionSource, DBOrderBean.class);
        } catch (Exception e) {
            Log.e(DatabaseHelper.class.getName(), "Unable to create datbases", e);
        }
    }

    /**
     * 更新SQLite数据库
     */
    @Override
    public void onUpgrade(
            SQLiteDatabase sqliteDatabase,
            ConnectionSource connectionSource,
            int oldVer,
            int newVer) {
        try {
            TableUtils.dropTable(connectionSource, DBOrderContentBean.class, true);
            TableUtils.dropTable(connectionSource,DBOrderBean.class,true);
            onCreate(sqliteDatabase, connectionSource);
        } catch (Exception e) {
            Log.e(DatabaseHelper.class.getName(),
                    "Unable to upgrade database from version " + oldVer + " to new "
                            + newVer, e);
        }
    }

    public Dao<DBOrderContentBean, Long> getDBOrderContentDao() throws SQLException {
        if (orderDao == null) {
            try {
                orderDao = getDao(DBOrderContentBean.class);
            } catch (Exception e) {

            }
        }
        return orderDao;
    }

    private Dao<DBOrderBean, Long> DBOrderBeanDao = null;

    public Dao<DBOrderBean, Long> getDBOrderBeanDao() throws SQLException {
        if (DBOrderBeanDao == null) {
            try {
                DBOrderBeanDao = getDao(DBOrderBean.class);
            } catch (Exception e) {
                return null;
            }
        }
        return DBOrderBeanDao;
    }


}
